package com.shizhanzhe.gxb.vip;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.crazysunj.cardslideview.CardViewPager;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.gxb.R;
import com.shizhanzhe.gxb.WXLoginActivity;
import com.shizhanzhe.gxb.base.UserBean;
import com.shizhanzhe.gxb.home.dialog.ShareWxPopupWindow;
import com.shizhanzhe.gxb.my.dialog.SignDialog;
import com.shizhanzhe.gxb.url.Path;
import com.shizhanzhe.gxb.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.gxb.utils.SharedPreferencesUtils;
import com.shizhanzhe.gxb.utils.Util;
import com.shizhanzhe.gxb.vip.activity.NoticeActivity;
import com.shizhanzhe.gxb.vip.bean.MyBean;
import com.shizhanzhe.gxb.vip.bean.Operation;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by YJ on 2019/1/8.
 */
public class VipFragment extends Fragment {
    Unbinder unbinder;
    //    @BindView(R.id.listview)
//    ListView listview;
    @BindView(R.id.viewpager)
    CardViewPager viewpager;
    private final int[] imageArray = {R.mipmap.pop_invite_bg, R.mipmap.pop_invite_bg2, R.mipmap.pop_invite_bg3};
    protected ImmersionBar mImmersionBar;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.iv_ewm)
    ImageView ivEwm;
    @BindView(R.id.invite_share)
    FrameLayout inviteShare;
    @BindView(R.id.progress_true)
    ProgressBar progressTrue;
    @BindView(R.id.zs_num)
    TextView zsNum;
    @BindView(R.id.progress_false)
    ProgressBar progressFalse;
    @BindView(R.id.fzs_num)
    TextView fzsNum;
    @BindView(R.id.jjjl)
    TextView jjjl;
    @BindView(R.id.zjjl)
    TextView zjjl;
    @BindView(R.id.zmsy)
    TextView zmsy;
    @BindView(R.id.iv_vip)
    ImageView ivVip;
    @BindView(R.id.vip_up)
    TextView vipUp;
    @BindView(R.id.scroll)
    ScrollView scroll;
    @BindView(R.id.jjjl_details)
    TextView jjjlDetails;
    @BindView(R.id.zjjl_details)
    TextView zjjlDetails;
    @BindView(R.id.zmsy_details)
    TextView zmsyDetails;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    private SignDialog mDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_vip, container, false);
        unbinder = ButterKnife.bind(this, view);
        initImmersionBar();
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ivEwm.setImageBitmap(Util.encodeAsBitmap(Path.invitereg(UserBean.uid)));
        initData();
    }

    private void initData() {
        final List<MyBean> list = new ArrayList<MyBean>();
        for (int s : imageArray) {
            list.add(new MyBean(s));
        }
        viewpager.bind(getChildFragmentManager(), new MyCardHandler(), list);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                Log.d("MainActivity", "position:" + position + " positionOffset:" + positionOffset + " positionOffsetPixels:" + positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                Log.d("PopPosterActivity", "position:" + position);
                Glide.with(getContext()).load(imageArray[position]).apply(new RequestOptions().error(R.mipmap.pop_invite_bg)).into(image);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.d("PopPosterActivity", "state:" + state);
            }
        });
        if (UserBean.uid != 0) {
            getoperation();
        }
//        viewpager.setCardTransformer(180, 0.38f);
//        viewpager.setCardPadding(15);
//        viewpager.setCardMargin(10);
        mDialog = new SignDialog(getContext());
        mDialog.setListener(new SignDialog.SignListener() {
            @Override
            public void checktrue() {
                mDialog.dismiss();
            }
        });

    }

    @OnClick({R.id.vip_up, R.id.invite_team, R.id.invite, R.id.vip_regular, R.id.vip_study})
    public void onViewClicked(View view) {
        if (UserBean.uid != 0) {
            switch (view.getId()) {
                case R.id.vip_up:
                    //vip升级
                    upgrade();
                    break;
                case R.id.invite_team:
                    //邀请好友加入我的团队
                    scroll.post(new Runnable() {
                        @Override
                        public void run() {
                            scroll.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                        }
                    });
                    break;
                case R.id.invite:
                    //立即邀请
                    Util.saveBitmap(getContext(), getBitmapByView(inviteShare), "/gxbinvite.jpg");
                    final ShareWxPopupWindow wxPopupWindow = new ShareWxPopupWindow(getActivity());
                    wxPopupWindow.setWxListener(new ShareWxPopupWindow.ShareWxListener() {
                        @Override
                        public void shareFriend() {
                            wxPopupWindow.dismiss();
                            Wechat.ShareParams sp = new Wechat.ShareParams();
                            sp.setImagePath(Environment.getExternalStorageDirectory() + "/test/gxbinvite.jpg");
                            sp.setShareType(Platform.SHARE_IMAGE);
                            Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                            weChat.share(sp);
                        }

                        @Override
                        public void shareCircle() {
                            wxPopupWindow.dismiss();
                            Platform.ShareParams weM = new Platform.ShareParams();
                            weM.setImagePath(Environment.getExternalStorageDirectory() + "/test/gxbinvite.jpg");
                            weM.setShareType(Platform.SHARE_IMAGE);
                            Platform WechatM = ShareSDK.getPlatform(WechatMoments.NAME);
                            WechatM.share(weM);
                        }

                        @Override
                        public void shareSave() {
                        }
                    });
                    wxPopupWindow.showDown2(viewpager);
                    break;
                case R.id.vip_regular:
                    //规则中心
                    if (UserBean.level>1) {
                        startActivity(new Intent(getContext(), NoticeActivity.class).putExtra("type", 2));
                    } else {
                        mDialog.show();
                        mDialog.notvip();
                    }
                    break;
                case R.id.vip_study:
                    //学习中心
                    if (UserBean.level>1) {
                        startActivity(new Intent(getContext(), NoticeActivity.class).putExtra("type", 1));
                    } else {
                        mDialog.show();
                        mDialog.notvip();
                    }
                    break;
                default:
            }
        } else {
            startActivity(new Intent(getContext(), WXLoginActivity.class));
        }
    }

    private void getoperation() {
        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.operation(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        Operation operation = new Gson().fromJson(json, Operation.class);
                        progressTrue.setProgress((int) ((double) operation.getZsnum() / 80 * 100));
                        progressFalse.setProgress((int) ((double) operation.getJjnum() / 160 * 100));
                        zsNum.setText("当前有效直属会员：" + operation.getZsnum() + "人");
                        fzsNum.setText("当前有效非直属会员：" + operation.getJjnum() + "人");
                        jjjl.setText("间接会员出单提升" + new DecimalFormat("######0").format((Double.parseDouble(operation.getSysparams().getProfittwo()) - Double.parseDouble(operation.getSysparams().getIncometwo())) / (Double.parseDouble(operation.getSysparams().getIncometwo())) * 100) + "%");
                        jjjlDetails.setText("(" + new DecimalFormat("######0").format(Double.parseDouble(operation.getSysparams().getIncometwo()) * 100) + "%--" + new DecimalFormat("######0").format(Double.parseDouble(operation.getSysparams().getProfittwo()) * 100) + "%)");
                        zjjl.setText("直接会员出单提升" + new DecimalFormat("######0").format((Double.parseDouble(operation.getSysparams().getProfitone()) - Double.parseDouble(operation.getSysparams().getIncomeone())) / (Double.parseDouble(operation.getSysparams().getIncomeone())) * 100) + "%");
                        zjjlDetails.setText("(" + new DecimalFormat("######0").format(Double.parseDouble(operation.getSysparams().getIncomeone()) * 100) + "%--" + new DecimalFormat("######0").format(Double.parseDouble(operation.getSysparams().getProfitone()) * 100) + "%)");
                        zmsy.setText("自买返佣收益提升" + new DecimalFormat("######0").format((Double.parseDouble(operation.getSysparams().getProfit()) - Double.parseDouble(operation.getSysparams().getIncome())) / (Double.parseDouble(operation.getSysparams().getIncome())) * 100) + "%");
                        zmsyDetails.setText("(" + new DecimalFormat("######0").format(Double.parseDouble(operation.getSysparams().getIncome()) * 100) + "%--" + new DecimalFormat("######0").format(Double.parseDouble(operation.getSysparams().getProfit()) * 100) + "%)");
                        UserBean.level = operation.getLevel();
                        SharedPreferencesUtils.setParam(getContext(), "level", UserBean.level);
//                        UserBean.level = 1;
                        if (UserBean.level > 0) {
                            vipUp.setVisibility(View.GONE);
                            ivVip.setImageResource(R.mipmap.is_vip);
                            tvVip.setText("      恭喜成为运营总监");
                        } else {
                            vipUp.setVisibility(View.VISIBLE);
                            ivVip.setImageResource(R.mipmap.not_vip);
                            tvVip.setText("      如何升级为运营总监");
                        }
                    } catch (Exception e) {
                        Toast.makeText(getContext(), "数据异常", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //升级
    private void upgrade() {
        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.upgrade(UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        JSONObject object = new JSONObject(json);
                        Toast.makeText(getContext(), object.getString("info"), Toast.LENGTH_SHORT).show();
                        if (object.getInt("status") == 1) {
                            getoperation();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "数据异常", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private Bitmap getBitmapByView(View headerView) {
        int h = headerView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(headerView.getWidth(), h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        headerView.draw(canvas);
        return bitmap;
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.keyboardEnable(true).navigationBarWithKitkatEnable(false).init();
        mImmersionBar.statusBarColor(R.color.gray_black)
                .init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mImmersionBar != null)
            ImmersionBar.with(this)
                    .statusBarColor(R.color.gray_black)
                    .init();
        getoperation();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
